#!/bin/bash

# 保持服务在线的脚本（持续发送心跳）

SERVICE_NAME="demo-service"
IP="127.0.0.1"
PORT="8888"
NACOS="http://localhost:8848"

echo "🚀 启动服务并保持在线..."
echo "  服务名: $SERVICE_NAME"
echo "  地址: $IP:$PORT"
echo ""

# 首次注册
echo "1️⃣  注册服务..."
curl -s -X POST "${NACOS}/nacos/v1/ns/instance" \
  -d "serviceName=$SERVICE_NAME" \
  -d "ip=$IP" \
  -d "port=$PORT" \
  -d "weight=1.0"
echo ""
echo "✅ 服务已注册"
echo ""

# 持续发送心跳
echo "💓 开始发送心跳（每 5 秒）..."
echo "   按 Ctrl+C 停止"
echo ""

count=0
while true; do
    sleep 5
    count=$((count + 1))
    
    # 发送心跳
    RESPONSE=$(curl -s -X PUT "${NACOS}/nacos/v1/ns/instance/beat" \
      -d "serviceName=$SERVICE_NAME" \
      -d "beat={\"ip\":\"$IP\",\"port\":$PORT,\"weight\":1.0}")
    
    if [ $((count % 6)) -eq 0 ]; then
        echo "💓 已发送 $count 次心跳 - $(date '+%H:%M:%S')"
    fi
done
